import { token } from '@/config/env';
import store from '@/store';

function request(options) {
    const { isLoading } = options || {};

    if (isLoading) {
        uni.showLoading({
            title: '加载中',
            mask: true
        });
    }

    if (!options.data) {
        options.data = {};
    }

    options.data.app = store.state.user.app || '';
    options.data.channelId = store.state.user.channelId || '';
    options.data.pId = store.state.user.pId || '';

    options.data.t = Date.parse(new Date());

    return new Promise((resolve, reject) => {
        uni.request({
            ...options,

            header: {
                Authorization: (token || uni.getStorageSync('token') || '').replace(/"/g, '')
            },

            success: res => {
                const { code, data, message } = res.data;

                switch (code) {
                    case 1000:
                        resolve(data);
                        break;
                    default:
                        reject(message);
                }

                resolve(data);
            },

            fail: err => {
                if (typeof err == 'string') {
                    reject(err);
                } else {
                    uni.showToast({
                        title: '系统有点累了，请稍后重试',
                        icon: 'none'
                    });
                    reject('系统有点累了，请稍后重试');
                }
            },

            complete: () => {
                if (isLoading) {
                    uni.hideLoading();
                }
            }
        });
    });
}

export { request };
